package com.appspot.yttv.client;

import java.util.ArrayList;
import java.util.List;

import com.appspot.yttv.client.model.Station;
import com.appspot.yttv.client.model.StationSource;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.Response;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.user.client.rpc.AsyncCallback;

/**
 * Retrieves the configurable stations.
 * 
 * @author Ramona Bobohalma
 *
 */
public class StationConfigurationService {
	
	private final static String configUrl = "stationlist"; 
	
	private final static StationSourceConverter sourceConverter = new StationSourceConverter();
	
	private static class ConfigurationCallback implements RequestCallback {
		
		private final AsyncCallback<List<Station>> callback;
		
		public ConfigurationCallback( AsyncCallback<List<Station>> callback) {
			this.callback = callback;
		}
		
		private native JavaScriptObject getObject(String text) /*-{
			return eval(text);
		}-*/;
	
		private List<Station> convertToStations(JsArray<StationEntry> stationEntries) {
			List<Station> stations = new ArrayList<Station>();
			for (int i=0; i < stationEntries.length(); ++i) {
				StationEntry stationEntry = stationEntries.get(i).cast();
				JsArray<StationSourceEntry> sources = stationEntry.getSources();
				List<String> urls = new ArrayList<String>();
				for(int j = 0; j < sources.length(); ++j) {
					StationSourceEntry sourceEntry = sources.get(j).cast(); 
					StationSource source = sourceConverter.toModel(sourceEntry);
					urls.addAll(FeedUrlProvider.forStationSource(source));
				}
				stations.add(new Station(stationEntry.getLabel(), new FeedPlaylistProvider(urls)));
			}
			return stations;
		}
	
		public void onError(Request request, Throwable exception) {
			// TODO Auto-generated method stub
		}

		public void onResponseReceived(Request request, Response response) {
			if (response.getStatusCode() == 200) {
				String responseText = response.getText();
				JavaScriptObject stationList = getObject(responseText);
				JsArray<StationEntry> stationEntries = stationList.cast();
				List<Station> stations = convertToStations(stationEntries); 
				callback.onSuccess(stations);
			} else {
				Console.log("GET " + configUrl + " failed with code " + response.getStatusCode());
			}
		}
	}
	
	/**
	 * Retrieves the configuration station list.
	 * 
	 * @param callback To notify with the station list. 
	 */
	public void findStations(final AsyncCallback<List<Station>> callback) {
		JsonRequest.doFetchURL(configUrl, new ConfigurationCallback(callback));
	}
}
